<template>
  <div class="home-wrapper">
    <!-- 顶部用户信息区域 -->
    <div class="user-info-section">
      <a-page-header :title="welcomeMessage">
        <template #subTitle>
          <span>所属部门：{{ departmentName }}</span>
        </template>
        <template #extra>
          <span class="date-info">{{ formattedDate }}</span>
        </template>

        <div class="user-detail-info">
          <div class="login-info">
            <p><AlertOutlined /> {{ lastLoginDetails }}</p>
            <p class="inspiration-text"><SmileOutlined spin /> {{ randomInspiration }}</p>
          </div>
          <div class="weather-info">
            <iframe
              width="100%"
              height="50"
              scrolling="no"
              frameborder="0"
              allowtransparency="true"
              src="https://i.tianqi.com/index.php?c=code&id=12&icon=1&num=3&site=12"
              alt="天气信息"
            ></iframe>
          </div>
        </div>
      </a-page-header>
    </div>

    <!-- 下方左右文档列表区域 - 优化布局 -->
    <div class="document-lists-container">
      <!-- 左侧：自己上传的文档列表 -->
      <div class="document-list-module left-module">
        <a-card title="已上传文档" :bordered="true" :hoverable="true">
          <!-- 列表操作栏 -->
          <div class="list-operations">
            <TableOperator
              v-model="myUploadsColumns"
              :tableId="'myUploads'"
              :refresh="loadMyUploads"
            />
          </div>

          <!-- 文档表格 -->
          <a-table
            :columns="myUploadsColumns"
            :dataSource="myUploadsData"
            :loading="myUploadsLoading"
            rowKey="docEntry"
            :scroll="{ x: 'max-content', y: 450 }"
            :pagination="false"
          >
            <template #bodyCell="{ text, record, column }">
              <template v-if="column.dataIndex === 'name'">
                <a @click="navigateToDetail(record.docEntry)">{{ text }}</a>
              </template>
              <template v-if="column.dataIndex === 'docPrivate'">
                <a-tag color="green" v-if="text === 'A'">公开</a-tag>
                <a-tag color="red" v-if="text === 'B'">私密</a-tag>
              </template>
              <template v-if="column.dataIndex === 'approved'">
                <a-tag color="green" v-if="text">已审核</a-tag>
                <a-tag color="orange" v-if="!text">未审核</a-tag>
              </template>
            </template>
          </a-table>

          <!-- 分页控件 -->
          <div class="pagination-control">
            <a-pagination
              :current="myUploadsPage.current"
              :pageSize="myUploadsPage.size"
              :total="myUploadsTotal"
              :pageSizeOptions="['10', '20', '50']"
              showSizeChanger
              showQuickJumper
              :showTotal="total => `共 ${total} 条`"
              @change="handleMyUploadsPageChange"
              @showSizeChange="handleMyUploadsSizeChange"
            />
          </div>
        </a-card>
      </div>

      <!-- 右侧：可查看的文档列表 -->
      <div class="document-list-module right-module">
        <a-card title="可查看文档" :bordered="true" :hoverable="true">
          <!-- 列表操作栏 -->
          <div class="list-operations">
            <TableOperator
              v-model="viewableColumns"
              :tableId="'viewableDocs'"
              :refresh="loadViewableDocs"
            />
          </div>

          <!-- 文档表格 -->
          <a-table
            :columns="viewableColumns"
            :dataSource="viewableData"
            :loading="viewableLoading"
            rowKey="docEntry"
            :scroll="{ x: 'max-content', y: 450 }"
            :pagination="false"
          >
            <template #bodyCell="{ text, record, column }">
              <template v-if="column.dataIndex === 'name'">
                <a @click="navigateToDetail(record.docEntry)">{{ text }}</a>
              </template>
              <template v-if="column.dataIndex === 'docPrivate'">
                <a-tag color="green" v-if="text === 'A'">公开</a-tag>
                <a-tag color="red" v-if="text === 'B'">私密</a-tag>
              </template>
              <template v-if="column.dataIndex === 'approved'">
                <a-tag color="green" v-if="text">已审核</a-tag>
                <a-tag color="orange" v-if="!text">未审核</a-tag>
              </template>
            </template>
          </a-table>

          <!-- 分页控件 -->
          <div class="pagination-control">
            <a-pagination
              :current="viewablePage.current"
              :pageSize="viewablePage.size"
              :total="viewableTotal"
              :pageSizeOptions="['10', '20', '50']"
              showSizeChanger
              showQuickJumper
              :showTotal="total => `共 ${total} 条`"
              @change="handleViewablePageChange"
              @showSizeChange="handleViewableSizeChange"
            />
          </div>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { computed, reactive, ref, onMounted } from 'vue';
  import { useUserStore } from '/@/store/modules/system/user';
  import { useRouter } from 'vue-router';
  import { AlertOutlined, SmileOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import uaparser from 'ua-parser-js';
  import { Solar, Lunar } from 'lunar-javascript';
  import _ from 'lodash';

  // 导入API和组件
  import { docmentApi } from '/@/api/business/file/docment-api.js';
  import TableOperator from '/src/components/support/table-operator/index.vue';
  import { columns } from '/@/views/business/file/docmentData/data.js';
  import heartSentenceArray from './heart-sentence';
  import { smartSentry } from '/src/lib/smart-sentry';

  // 初始化路由和状态
  const router = useRouter();
  const userStore = useUserStore();
  const userId = computed(() => userStore.$state.userId || '');

  // 顶部用户信息相关
  const departmentName = computed(() => userStore.departmentName || '未知部门');

  const welcomeMessage = computed(() => {
    const hour = new Date().getHours();
    let greeting = '晚上好';

    if (hour >= 0 && hour <= 6) greeting = '午夜好';
    else if (hour > 6 && hour <= 11) greeting = '早上好';
    else if (hour > 11 && hour <= 14) greeting = '中午好';
    else if (hour > 14 && hour <= 18) greeting = '下午好';

    return `${greeting}，${userStore.$state.actualName || '用户'}`;
  });

  const lastLoginDetails = computed(() => {
    const details = [];

    if (userStore.$state.lastLoginTime) {
      details.push(`上次登录: ${userStore.$state.lastLoginTime}`);
    }

    if (userStore.$state.lastLoginUserAgent) {
      const ua = uaparser(userStore.$state.lastLoginUserAgent);
      const deviceInfo = [];
      if (ua.browser.name) deviceInfo.push(ua.browser.name);
      if (ua.os.name) deviceInfo.push(ua.os.name);
      if (deviceInfo.length) details.push(`设备: ${deviceInfo.join(' ')}`);
    }

    if (userStore.$state.lastLoginIpRegion) {
      details.push(userStore.$state.lastLoginIpRegion);
    }

    return details.length ? details.join('; ') : '首次登录，欢迎使用';
  });

  const formattedDate = computed(() => {
    const solar = Solar.fromDate(new Date());
    const lunar = Lunar.fromDate(new Date());
    const nextTerm = lunar.getNextJieQi();

    return `${solar.toString()} 星期${solar.getWeekInChinese()}，农历${lunar.getMonthInChinese()}月${lunar.getDayInChinese()}（${lunar.getPrevJieQi().getName()}，${nextTerm.getName()} ${nextTerm.getSolar().toYmd()}）`;
  });

  const randomInspiration = computed(() => {
    return heartSentenceArray.length
      ? heartSentenceArray[_.random(0, heartSentenceArray.length - 1)]
      : '每一天都是新的开始';
  });

  // 左侧：自己上传的文档列表相关
  const myUploadsPage = reactive({
    current: 1,
    size: 10
  });
  const myUploadsData = ref([]);
  const myUploadsTotal = ref(0);
  const myUploadsLoading = ref(false);
  const myUploadsColumns = ref([...columns]);

  // 右侧：可查看的文档列表相关
  const viewablePage = reactive({
    current: 1,
    size: 10
  });
  const viewableData = ref([]);
  const viewableTotal = ref(0);
  const viewableLoading = ref(false);
  const viewableColumns = ref([...columns]);

  // 加载自己上传的文档
  const loadMyUploads = async () => {
    myUploadsLoading.value = true;
    try {
      const params = {
        pageNum: myUploadsPage.current,
        pageSize: myUploadsPage.size,
        uploadUserId: userId.value // 筛选当前用户上传的文档
      };

      const response = await docmentApi.queryMyPage(params);
      myUploadsData.value = response.data?.list || [];
      myUploadsTotal.value = response.data?.total || 0;
    } catch (error) {
      console.error('加载自己上传的文档失败:', error);
      smartSentry.captureError(error);
      myUploadsData.value = [];
      myUploadsTotal.value = 0;
    } finally {
      myUploadsLoading.value = false;
    }
  };

  // 加载可查看的文档
  const loadViewableDocs = async () => {
    viewableLoading.value = true;
    try {
      const params = {
        pageNum: viewablePage.current,
        pageSize: viewablePage.size,
        viewUserId: userId.value // 筛选当前用户可查看的文档
      };

      const response = await docmentApi.queryPage(params);
      viewableData.value = response.data?.list || [];
      viewableTotal.value = response.data?.total || 0;
    } catch (error) {
      console.error('加载可查看的文档失败:', error);
      smartSentry.captureError(error);
      viewableData.value = [];
      viewableTotal.value = 0;
    } finally {
      viewableLoading.value = false;
    }
  };

  // 分页处理函数
  const handleMyUploadsPageChange = (page) => {
    myUploadsPage.current = page;
    loadMyUploads();
  };

  const handleMyUploadsSizeChange = (current, size) => {
    myUploadsPage.current = current;
    myUploadsPage.size = size;
    loadMyUploads();
  };

  const handleViewablePageChange = (page) => {
    viewablePage.current = page;
    loadViewableDocs();
  };

  const handleViewableSizeChange = (current, size) => {
    viewablePage.current = current;
    viewablePage.size = size;
    loadViewableDocs();
  };

  // 导航函数
  const navigateToDetail = (docEntry) => {
    router.push({ path: 'file/docmenta', query: { type: 'info', docEntry } });
  };

  const navigateToCreate = () => {
    router.push({ path: 'file/docmenta', query: { type: 'new', docEntry: null } });
  };

  // 页面初始化
  onMounted(async () => {
    // 确保用户信息已加载
    if (!userStore.$state.actualName) {
      await userStore.getUserInfo().catch(error => {
        console.error('获取用户信息失败:', error);
        smartSentry.captureError(error);
      });
    }

    // 并行加载两个列表数据
    await Promise.all([
      loadMyUploads(),
      loadViewableDocs()
    ]);
  });
</script>

<style scoped lang="less">
  .home-wrapper {
    width: 100%;
    padding: 16px;
    box-sizing: border-box;
    background-color: #f5f5f5;
    min-height: 100vh;
  }

  /* 顶部用户信息区域样式 */
  .user-info-section {
    background: #fff;
    border-radius: 6px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    margin-bottom: 20px;
    padding: 16px;

    .user-detail-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 12px;

      .login-info {
        flex: 1;
        min-width: 0;

        p {
          margin: 0 0 8px 0;
          font-size: 13px;
          color: #333;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .inspiration-text {
          color: #888;
          font-size: 12px;
        }
      }

      .weather-info {
        width: 400px;
        min-width: 400px;
      }
    }

    .date-info {
      color: #666;
      font-size: 14px;
    }
  }

  /* 下方文档列表容器样式 - 优化为更清晰的双列布局 */
  .document-lists-container {
    display: flex;
    gap: 20px;
    width: 100%;
    box-sizing: border-box;
    // 确保容器占据足够空间
    min-height: 600px;
  }

  /* 单个文档列表模块样式 - 增强视觉区分 */
  .document-list-module {
    flex: 1; /* 左右各占50%宽度 */
    box-sizing: border-box;
    // 增加阴影和边框，使两个模块更清晰分离
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
    border-radius: 6px;
    overflow: hidden;
  }

  // 为左右模块添加细微差异，增强区分度
  .left-module {
    border: 1px solid #e8f4ea;
  }

  .right-module {
    border: 1px solid #f0f2f5;
  }

  /* 列表操作栏样式 */
  .list-operations {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-top: 8px;
  }

  /* 分页控件样式 */
  .pagination-control {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
    padding: 8px 0;
  }

  /* 响应式适配 */
  @media (max-width: 1200px) {
    .document-lists-container {
      flex-direction: column;
      gap: 16px;
    }

    .user-info-section .user-detail-info {
      flex-direction: column;
      align-items: flex-start;

      .weather-info {
        width: 100%;
        min-width: auto;
        margin-top: 12px;
      }
    }
  }

  @media (max-width: 768px) {
    .home-wrapper {
      padding: 8px;
    }

    .list-operations {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;
    }
  }
</style>
